package com.example.exchangeapp.yy.fragment;

import static android.content.ContentValues.TAG;

import static com.example.exchangeapp.yy.constant.AppId.AppId;
import static com.example.exchangeapp.yy.constant.AppSecret.appSecret;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Handler;
import android.os.Looper;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.exchangeapp.R;
import com.example.exchangeapp.zjs.GetUserStatus;
import com.example.exchangeapp.zjs.ImageSliderAdapter;
import com.example.exchangeapp.zjs.Product;
import com.example.exchangeapp.zjs.ProductAdapter;
import com.example.exchangeapp.zjs.ProductDetailActivity;
import com.example.exchangeapp.zjs.ProductResponse;
import com.example.exchangeapp.zjs.ProductResponse2;
import com.example.exchangeapp.zjs.SearchResultActivity;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class IndexFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;

    //zjs---轮播图
    private ViewPager2 viewPager2;
    private ImageSliderAdapter imageSliderAdapter;
    private List<Integer> imageList = new ArrayList<>();
    private int currentPosition = 0;
    private Handler handler = new Handler();
    private Runnable runnable;

    //请求获取到的商品列表
    private List<Product> productList;
    private RecyclerView recyclerView;
    private final Gson gson = new Gson();
    private Handler uiHandler = new Handler(Looper.getMainLooper());

    // 用于保存轮播图的初始高度
    private int initialViewPagerHeight;


    public IndexFragment() {}

    public static IndexFragment newInstance(String param1, String param2) {
        IndexFragment fragment = new IndexFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    //搜索框
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_index, container, false);

        //--------搜索框部分-------
        Toolbar toolbar = view.findViewById(R.id.toolbar);
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        if (activity != null) {
            activity.setSupportActionBar(toolbar);
        }

        // 设置自定义布局
        toolbar.setContentInsetsAbsolute(0, 0); // 去除默认的左右间距
        toolbar.setContentInsetsRelative(0, 0); // 去除默认的左右间距
        toolbar.addView(inflater.inflate(R.layout.toolbar_search, toolbar, false));


        // 获取搜索框和搜索按钮
        EditText editTextSearch = toolbar.findViewById(R.id.editText_search);
        ImageView searchButton = toolbar.findViewById(R.id.imageView_search);

        // 设置搜索按钮点击事件
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入的商品名称
                String searchProductName = editTextSearch.getText().toString().trim();
                // 跳转到 SearchResultActivity，并传递查询关键词
                Intent intent = new Intent(getActivity(), SearchResultActivity.class);
                intent.putExtra("searchProductName", searchProductName);
                startActivity(intent);
            }
        });

        // 设置搜索框焦点变化事件监听器
        editTextSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // 在搜索框获取焦点时，设置边框样式为黄色，并显示键盘
                if (hasFocus) {
                    editTextSearch.setBackgroundResource(R.drawable.edittext_focused_border);
                } else {
                    //在搜索框失去焦点时，设置边框样式为灰色
                    editTextSearch.setBackgroundResource(R.drawable.edittext_default_border);
                }
            }
        });


        //--------轮播图部分-------
        viewPager2 = view.findViewById(R.id.viewPager);

        imageList.add(R.drawable.image1);
        imageList.add(R.drawable.image2);
        imageList.add(R.drawable.image3);

        imageSliderAdapter = new ImageSliderAdapter(requireContext(), imageList, viewPager2);
        viewPager2.setAdapter(imageSliderAdapter);

        // 保存轮播图的初始高度
        viewPager2.post(new Runnable() {
            @Override
            public void run() {
                initialViewPagerHeight = viewPager2.getHeight();
            }
        });

        //商品列表
        recyclerView = view.findViewById(R.id.recyclerView);

        //请求商品数据
        getProductTotal();

        // 瀑布流布局
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        return view;
    }


    //轮播图
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 启动自动轮播
        startAutoScroll();

        // 监听RecyclerView的滚动事件，使轮播图随着滑动改变高度
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 获取RecyclerView滚动的偏移量
                int scrollOffset = recyclerView.computeVerticalScrollOffset();

                // 根据滚动偏移量调整轮播图的高度
                int newViewPagerHeight = initialViewPagerHeight - scrollOffset;
                // 限制轮播图高度的最小值
                newViewPagerHeight = Math.max(newViewPagerHeight, 0);
                // 设置调整后的轮播图高度
                viewPager2.getLayoutParams().height = newViewPagerHeight;
                viewPager2.requestLayout();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopAutoScroll();
    }

    private void startAutoScroll() {
        int interval = 3000;
        runnable = new Runnable() {
            @Override
            public void run() {
                currentPosition++;
                if (currentPosition >= imageList.size()) {
                    currentPosition = 0;
                }
                viewPager2.setCurrentItem(currentPosition, true);

                handler.postDelayed(this, interval);
            }
        };

        handler.postDelayed(runnable, interval);
    }
    private void stopAutoScroll() {
        handler.removeCallbacks(runnable);
    }



    //get请求商品总数
    private void getProductTotal(){
        new Thread(() -> {
            //用户id
            int id = 67;
//            int id = 0;
            Context context = getActivity().getApplicationContext();
            //GetUserStatus getUserStatus=new GetUserStatus(getActivity());
            GetUserStatus getUserStatus=new GetUserStatus(context);
            Cursor cursor=getUserStatus.getDataFromDatabase();
            while (cursor.moveToNext()){
                int index0=cursor.getColumnIndex("ID");
                id=cursor.getInt(index0);
            }
            String userId = (String.valueOf(id));
            System.out.println("请求商品的用户id为"+userId);
            // 请求的url路径
            String url = "http://47.107.52.7:88/member/tran/goods/all?userId="+userId;

            //我的f9ed7014c8cb45169ab4cc0728775790和26073a2f31b8baca64eca93c3c2c5a3dd2313
            //yy的ea0f4556cf414613a551ca2c25840189和139172f805f8d3e654ffb891d963d96f64f62
            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId)
                    .add("appSecret", appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callbackProductTotal);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callbackProductTotal = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "连接服务器失败!");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("json串为", body);
            // 解析json串到自己封装的状态
            ProductResponse dataResponseBody = gson.fromJson(body, ProductResponse.class);
            Log.d("商品信息为", "商品信息为"+dataResponseBody.toString());

            //获取商品总数
            Integer productTotal = dataResponseBody.getData().getTotal();
            System.out.println("商品总数为："+productTotal);

            // 获取商品数据
            getProduct(productTotal);
        }
    };

    //get请求商品数据
    private void getProduct(Integer productTotal){
        new Thread(() -> {
            //用户id
            int id = 67;
//            int id = 0;
            Context context = getActivity().getApplicationContext();
            //GetUserStatus getUserStatus=new GetUserStatus(getActivity());
            GetUserStatus getUserStatus=new GetUserStatus(context);
            Cursor cursor=getUserStatus.getDataFromDatabase();
            while (cursor.moveToNext()){
                int index0=cursor.getColumnIndex("ID");
                id=cursor.getInt(index0);
            }
            String userId = (String.valueOf(id));
            System.out.println("请求商品的用户id为"+userId);
            // 请求的url路径
            String url = "http://47.107.52.7:88/member/tran/goods/all?size="+productTotal+"&userId="+userId;

            //我的f9ed7014c8cb45169ab4cc0728775790和26073a2f31b8baca64eca93c3c2c5a3dd2313
            //yy的ea0f4556cf414613a551ca2c25840189和139172f805f8d3e654ffb891d963d96f64f62
            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId)
                    .add("appSecret", appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callbackProduct);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callbackProduct = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "连接服务器失败!");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("json串为", body);
            // 解析json串到自己封装的状态
            ProductResponse dataResponseBody = gson.fromJson(body, ProductResponse.class);
            Log.d("商品信息为", "商品信息为"+dataResponseBody.toString());

            // 获取商品列表
            productList = dataResponseBody.getData().getRecords();

            // 使用Handler在主线程中更新UI
            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    // 在这里创建适配器并设置到RecyclerView
                    ProductAdapter adapter = new ProductAdapter(productList);
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    };
}